﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace RemoteSpark
{
    class SparkIo
    {
        private const string DeviceId = "123412341234132412341234";
        private const string Token = "0986709780987097809709709809787907890092";
        internal async static Task<LedResponse> Set(string p1, string p2)
        {
            LedResponse result = null;

            using (var request = new HttpClient())
            {
                string postData = string.Format("params={0},{1}", p1, p2);
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                var stringContent = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
                request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                var response = await request.PostAsync(string.Format("https://api.spark.io/v1/devices/{0}/led", DeviceId), stringContent);
                var json = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<LedResponse>(json);
                result.PlainJson = json;
                if (result.return_value == "1")
                    result.ok = true;
            }
            return result;
        }

        internal async static Task<TemperatureResponse> GetTemperature()
        {
            TemperatureResponse result = null;
            using (var request = new HttpClient())
            {
                request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                request.DefaultRequestHeaders.IfModifiedSince = DateTime.Now;
                var response = await request.GetAsync(string.Format("https://api.spark.io/v1/devices/{0}/temperature", DeviceId));
                var json = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<TemperatureResponse>(json);
            }
            return result;
        }
    }
}
